//
//  CacheDaoForfficalNews.m
//  GolfFriend
//
//  Created by Vescky on 14-2-28.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "CacheDaoForfficalNews.h"
#import "JSON.h"
#import "DateUtility.h"

#define TB_OFFICAL_NEWS_CACHE @"OFFICAL_NEWS_CACHE"

@implementation CacheDaoForfficalNews

static CacheDaoForfficalNews *cDaoForOfficalNews;

+ (id)shareCacheDaoForfficalNews {
    if (!cDaoForOfficalNews) {
        cDaoForOfficalNews = [[CacheDaoForfficalNews alloc] init];
        DB *dbase = [[DB alloc] init];
        FMDatabase *database = [dbase getDatabase];
        [database executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(recordId integer primary key,newsId text,comments text,zan text,clicks text,title text,content text,sourceLinks text,newsType text,isSupported text)",TB_OFFICAL_NEWS_CACHE]];
        [database close];
    }
    return cDaoForOfficalNews;
}

//更新单个
- (bool)updateCacheDataWithNewsContent:(NSDictionary*)dict {
    if ([[[dict objectForKey:@"id"] lowercaseString] stringByMatching:@"null"]) {
        return NO;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[dict objectForKey:@"id"] ? [dict objectForKey:@"id"] : @"'null'",@"newsId",
                                  [dict objectForKey:@"comments"] ? [dict objectForKey:@"comments"] : @"'0'",@"comments",
                                  [dict objectForKey:@"zan"] ? [dict objectForKey:@"zan"] : @"'0'",@"zan",
                                  [dict objectForKey:@"clicks"] ? [dict objectForKey:@"clicks"] : @"'0'",@"clicks",
                                  [dict objectForKey:@"title"] ? [dict objectForKey:@"title"] : @"''",@"title",
                                  [dict objectForKey:@"content"] ? [dict objectForKey:@"content"] : @"''",@"content",
                                  [[dict objectForKey:@"sourceLinks"] JSONFragment] ? [[dict objectForKey:@"sourceLinks"] JSONFragment] : @"''",@"sourceLinks",
                                  [dict objectForKey:@"newsType"] ? [dict objectForKey:@"newsType"] : @"'0'",@"newsType",
                                  [dict objectForKey:@"isSupported"] ? [dict objectForKey:@"isSupported"] : @"0",@"isSupported" ,nil];
    
    if (!params || [params count] < 1) {
        return NO;
    }
    
    if ([self isRecordExist:[params objectForKey:@"newsId"]]) {
        //有记录的，update
        [self update:params where:[[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"newsId"],@"newsId",nil] inTable:TB_OFFICAL_NEWS_CACHE];
    }
    else {
        //无记录的，insert
        [self insert:params inTable:TB_OFFICAL_NEWS_CACHE];
    }
    
    return YES;
}

//更新一个数组
- (bool)updateCacheDataWithNewsContentArray:(NSArray*)nArray {
    if (nArray.description.length < 1) {
        return NO;
    }
    if (![nArray respondsToSelector:@selector(count)]) {
        return NO;
    }
    for (int i = 0; i < [nArray count]; i++) {
        NSDictionary *dict = [nArray objectAtIndex:i];
        if (dict) {
            [self updateCacheDataWithNewsContent:dict];
        }
    }
    return YES;
}

//获取一个数组
- (NSMutableArray*)getCacheDataLimitRow:(NSRange)limitRange newsType:(int)nType {
    
    NSString *sqlString = [NSString stringWithFormat:@"select * from %@ where newsType = '%d'",TB_OFFICAL_NEWS_CACHE,nType];
    
    NSMutableArray *allData = [self queryByConfition:sqlString];//[self queryAll:TB_OFFICAL_NEWS_CACHE];
    
    //去除空数据
    NSMutableIndexSet *delIndexSet = [[NSMutableIndexSet alloc] init];
    for (int i = 0; i < [allData count]; i++) {
        NSString *newId = [[[allData objectAtIndex:i] objectForKey:@"newsId"] lowercaseString];
        if ([newId stringByMatching:@"null"]) {
            [delIndexSet addIndex:i];
        }
    }
    if ([delIndexSet count] > 0) {
        [allData removeObjectsAtIndexes:delIndexSet];
    }
    
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([allData count] > limitRange.length) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[allData subarrayWithRange:limitRange]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:allData];
    }
    
    for (int i = 0; i < [arrLimitted count]; i++) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithDictionary:[allData objectAtIndex:i]];
        NSDictionary *sourceDict = [[_dict objectForKey:@"sourceLinks"] JSONValue];
        if (sourceDict) {
            [_dict setObject:sourceDict forKey:@"sourceLinks"];
        }
        [arrLimitted replaceObjectAtIndex:i withObject:_dict];
    }
    
    //按时间，从晚到早排序
    NSArray *sortedArr = [arrLimitted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj1 objectForKey:@"time"]);
        NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj2 objectForKey:@"time"]);
        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

//获取单个
- (NSDictionary*)getCacheDataWithNewsId:(NSString*)nId {
    NSString *sqlString = [NSString stringWithFormat:@"select * from %@ where newsId = '%@'",TB_OFFICAL_NEWS_CACHE,nId];
    NSMutableArray *rArr = [self queryByConfition:sqlString];
    if (rArr && [rArr count] > 0) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithDictionary:[rArr objectAtIndex:0]];
        [_dict setObject:nId forKey:@"id"];
        [_dict removeObjectForKey:@"newsId"];
        return _dict;
    }
    
    return nil;
}

//清除缓存
- (bool)cleanupCache {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    bool flag = [database executeUpdate:[NSString stringWithFormat:@"delete from %@",TB_OFFICAL_NEWS_CACHE]];
    if (flag) {
        flag = [database executeUpdate:[NSString stringWithFormat:@"update sqlite_sequence set seq=0 where name = '%@'",TB_OFFICAL_NEWS_CACHE]];
        
    }
    [database close];
    return flag;
}


#pragma mark - Private
- (bool)isRecordExist:(NSString*)nId {
    if ([self getCacheDataWithNewsId:nId]) {
        return YES;
    }
    return NO;
}

@end
